package com.longe.netty.protobufTwo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufEncoder;

/**
 * 客户端
 */
public class NettyProtoBufClient {

    private final static String IP = "127.0.0.1";
    private final static Integer PORT = 9999;

    public static void main(String[] args) {

        //客户端事件循环组
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            //创建客户端启动对象
            Bootstrap bootstrap = new Bootstrap();
            //设置参数
            bootstrap.group(group) //设置线程组
                    .channel(NioSocketChannel.class) //使用NioSocketChannel作为客户端的通道实现
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            //给管道(pipeline)添加处理器
                            ChannelPipeline pipeline = ch.pipeline();
                            //在pipeline中加入 ProtoBufEncoder
                            pipeline.addLast("encoder", new ProtobufEncoder());
                            //添加自定义的handler
                            pipeline.addLast(new NettyProtoBufClientHandler());
                        }
                    });

            System.err.println("客户端 ok......");
            //启动客户端连接服务器
            ChannelFuture channelFuture = bootstrap.connect(IP, PORT).sync();

            //关闭通道进行监听
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }
}
